package com.jsh.erp.service.project;

import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.datasource.vo.DepotHeadVo4StatementAccount;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.accountHead.AccountHeadService;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.BaseResponseInfo;
import com.jsh.erp.utils.ExcelUtils;
import com.jsh.erp.utils.StringUtil;
import com.jsh.erp.utils.Tools;
import jxl.Sheet;
import jxl.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;


@Service
public class ProjectService {
    private Logger logger = LoggerFactory.getLogger(ProjectService.class);

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private ProjectMapperEx projectMapperEx;
    @Resource
    private LogService logService;
    @Resource
    private UserService userService;
    @Resource
    private AccountHeadMapperEx accountHeadMapperEx;
    @Resource
    private DepotHeadMapperEx depotHeadMapperEx;
    @Resource
    private AccountItemMapperEx accountItemMapperEx;
    @Resource
    private DepotHeadService depotHeadService;
    @Resource
    private AccountHeadService accountHeadService;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private UserBusinessService userBusinessService;

    public Project getProject(long id)throws Exception {
        Project result=null;
        try{
            result=projectMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<Project> getProjectListByIds(String ids)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        List<Project> list = new ArrayList<>();
        try{
            ProjectExample example = new ProjectExample();
            example.createCriteria().andIdIn(idList);
            list = projectMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Project> getProject()throws Exception {
        ProjectExample example = new ProjectExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Project> list=null;
        try{
            list=projectMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Project> select(String name, String type, String phonenum,String contacts, String groupName, String roleType, int offset, int rows) throws Exception{
        List<Project> resList = new ArrayList<Project>();
        try{
            String [] creatorArray = depotHeadService.getCreatorArray(roleType);
            List<Project> list = projectMapperEx.selectByConditionProject(name, type, phonenum, contacts, groupName, creatorArray, offset, rows);
            for(Project s : list) {
                resList.add(s);
            }
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return resList;
    }

    public Long countProject(String supplier, String type, String phonenum, String contacts,String groupName, String roleType) throws Exception{
        Long result=null;
        try{
            String [] creatorArray = depotHeadService.getCreatorArray(roleType);
            result=projectMapperEx.countsByProject(supplier, type, phonenum, contacts,groupName, creatorArray);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertProject(JSONObject obj, HttpServletRequest request)throws Exception {
        Project project = JSONObject.parseObject(obj.toJSONString(), Project.class);
        int result=0;
        try{
            project.setEnabled(true);
            User userInfo=userService.getCurrentUser();
            project.setCreator(userInfo==null?null:userInfo.getId());
            result=projectMapper.insertSelective(project);

            logService.insertLog("项目",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(project.getName()).toString(),request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateProject(JSONObject obj, HttpServletRequest request)throws Exception {
        Project project = JSONObject.parseObject(obj.toJSONString(), Project.class);
        int result=0;
        try{
            result=projectMapper.updateByPrimaryKeySelective(project);
            logService.insertLog("项目",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(project.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteProject(Long id, HttpServletRequest request)throws Exception {
        return batchDeleteProjectByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteProject(String ids, HttpServletRequest request) throws Exception{
        return batchDeleteProjectByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteProjectByIds(String ids)throws Exception {
        int result=0;
        String [] idArray=ids.split(",");

        //记录日志
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<Project> list = getProjectListByIds(ids);
        for(Project project: list){
            sb.append("[").append(project.getName()).append("]");
        }
        logService.insertLog("项目", sb.toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        User userInfo=userService.getCurrentUser();
        //校验通过执行删除操作
        try{
            result = projectMapperEx.batchDeleteProjectByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    public int checkIsNameExist(Long id, String name)throws Exception {
        ProjectExample example = new ProjectExample();
        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Project> list=null;
        try{
            list= projectMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list==null?0:list.size();
    }

    public int checkIsNameAndTypeExist(Long id, String name, String type)throws Exception {
        name = name == null? "": name;
        ProjectExample example = new ProjectExample();
        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andTypeEqualTo(type)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Project> list=null;
        try{
            list= projectMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list==null?0:list.size();
    }

    public List<Project> findBySelect()throws Exception {
        ProjectExample example = new ProjectExample();
        example.createCriteria().andEnabledEqualTo(true).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("sort asc, id desc");
        List<Project> list=null;
        try{
            list = projectMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Project> findBySelectType(String type)throws Exception {
        ProjectExample example = new ProjectExample();
        example.createCriteria().andTypeLike(type).andEnabledEqualTo(true).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("sort asc, id desc");
        List<Project> list=null;
        try{
            list = projectMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Project> findById(Long supplierId)throws Exception {
        ProjectExample example = new ProjectExample();
        example.createCriteria().andIdEqualTo(supplierId)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("sort asc, id desc");
        List<Project> list=null;
        try{
            list = projectMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }



    public List<Project> findByAll(String name, String type, String phonenum, String groupName, String contacts) throws Exception{
        List<Project> list=null;
        try{
            list = projectMapperEx.findByAll(name, type, phonenum, contacts, groupName);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public BigDecimal parseBigDecimalEx(String str)throws Exception{
        if(!StringUtil.isEmpty(str)) {
            return new BigDecimal(str);
        } else {
            return null;
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetStatus(Boolean status, String ids)throws Exception {
        logService.insertLog("项目",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ENABLED).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        List<Long> supplierIds = StringUtil.strToLongList(ids);
        Project project = new Project();
        project.setEnabled(status);
        ProjectExample example = new ProjectExample();
        example.createCriteria().andIdIn(supplierIds);
        int result=0;
        try{
            result = projectMapper.updateByExampleSelective(project, example);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
}
